const fs = require("fs");
const iconv = require("iconv-lite");
const ini = require("ini");

/**
 * 读取配置文件
 * @param {*} filePath 
 * @returns 
 */
const readini = (filePath) => {
  try {
    let config = ini.parse(fs.readFileSync(filePath, "utf-8"));
    // 转换带有 null prototype 的对象为普通对象
    function toPlainObject(obj) {
      return JSON.parse(JSON.stringify(obj));
    }

    // 转换配置数据为普通对象
    config = toPlainObject(config);

    // console.log(`读取配置文件：`, config);
    return { code: 200, msg: "读取配置文件成功", data: config };
  } catch(err) {
    return { code: 300, msg: "读取配置文件出错：" + err };
  }
}
/**
 * 写入配置文件
 * @param {*} filePath 
 * @param {*} config 
 * @returns 
 */
const writeini = (filePath,config) => {
  try {
    // 将修改后的对象转成 .ini 格式字符串并写回文件
    fs.writeFileSync(filePath, ini.stringify(config));
    return { code: 200,msg:"更新配置文件成功", data: config };
  } catch (err) {
    console.log('更新配置文件出错：',err)
    return { code: 300, msg: "读取配置文件出错：" + err };
  }
};
/**
 * 同步读日志文件
 * @param {*} filePath 
 * @returns 
 */
const readDocument = (filePath) => {
  try {
    let data = fs.readFileSync(filePath);
    data = iconv.decode(data, "GBK");
    const lines = data.split(/\r\n/);
    let res = {
      code: 200,
      msg: "读取文件成功",
      data: lines,
    };
    return res;
  } catch(err) {
    let res = {
      code: 300,
      msg: "读取文件失败" + err,
    };
    return res;
  }
};
/**
 * 异步读日志文件
 * @param {*} filePath 
 * @returns 
 */
const asyncReadDocument = (filePath) => {
  return new Promise((resolve, reject) => {
    // 读取文件并将内容从 GBK 转为 UTF-8
    fs.readFile(filePath, (err, data) => {
      if (err) {
        // console.error("444读取文件出错:", err);
        let res = {
          code: 300,
          msg: "读取文件出错:" + err,
        };
        resolve(res);
        return;
      }
      // 将 GBK 编码的 Buffer 转换为 UTF-8 字符串
      const utf8Content = iconv.decode(data, "GBK");
      const lines = utf8Content.split(/\r\n/);;
      let res = {
        code: 200,
        msg: "读取文件成功",
        data: lines,
      };
      resolve(res);
    });
  });
};
/**
 * 同步写入文件 写入内容空时创空文件
 * @param {*} filePath 
 * @param {*} data 
 * @param {append为末尾追加<默认>,cover为覆盖} type 
 * @returns 
 */
const writeDocument = (filePath, data, type = "append") => {
  try {
    // 转换数据为字符串
    const dataString = JSON.stringify(data, null, 2); // 格式化为 JSON 字符串（也可以使用其他格式）
    // 将数据写入 .txt 文件
    if ((type = "append")) {
      // 追加数据到 .txt 文件
      fs.appendFileSync(filePath, dataString + "\n", "utf8");
    } else if (type == "cover") {
      fs.writeFileSync(filePath, dataString, "utf8");
    } else {
      return {
        code: 300,
        msg: "参数类型错误",
      };
    }

    let res = {
      code: 200,
      msg: "读取文件成功",
    };
    return res;
  } catch (err) {
    let res = {
      code: 300,
      msg: "读取文件失败" + err,
    };
    return res;
  }
};
/**
 * 异步写入文档  写入内容空时创空文件
 * @param {*} filePath 
 * @param {*} data 
 * @param {append为末尾追加<默认>,cover为覆盖} type 
 * @returns 
 */
const asyncWriteDocument = (filePath, data, type = "append") => {
  try {
    // 转换数据为字符串
    const dataString = JSON.stringify(data, null, 2); // 格式化为 JSON 字符串（也可以使用其他格式）
    // 设置文件路径
    // const filePath = path.join(__dirname, "data.txt");
    return new Promise((resolve, reject) => {
      let write = fs.appendFile
      if ((type = "append")) {
        write = fs.appendFile;
      } else if (type == "cover") {
        write = fs.writeFile;
      } else {
        return {
          code: 300,
          msg: "参数类型错误",
        };
      }
      write(filePath, dataString, "utf8", (err) => {
        if (err) {
          console.error("写入失败:", err);
          let res = {
            code: 300,
            msg: "写入失败:" + err,
          };
          resolve(res);
        } else {
          console.log("数据已成功写入文件:", filePath);
          let res = {
            code: 200,
            msg: "数据已成功写入文件",
          };
          resolve(res);
        }
      });
    });
  } catch (err) {
    let res = {
      code: 300,
      msg: "读取文件失败" + err,
    };
    return res;
  }
};
/**
 * 同步删除文件
 * @param {*} filePath 
 * @returns 
 */
const deleteFile = (filePath) => {
  try {
    // 删除文件
    fs.unlinkSync(filePath);
    console.log(`文件已成功删除: ${filePath}`);
    let res = {
      code: 200,
      msg: "文件已成功删除",
    };
    return res;
  } catch (err) {
    let res = {
      code: 300,
      msg: "文件删除失败" + err,
    };
    return res;
  }
};
/**
 * 异步删除文件
 * @param {*} filePath 
 * @returns 
 */
const asyncDeleteFile = (filePath) => {
  return new Promise((resolve, reject) => {
    // 异步删除文件
    fs.unlink(filePath, (err) => {
      if (err) {
        let res = {
          code: 300,
          msg: "删除文件时发生错误:"+err,
        };
        resolve(res);
        return;
      } else {
        let res = {
          code: 200,
          msg: `文件已成功删除: ${filePath}`,
        };
        resolve(res);
      }
    });
  });
};
/**
 * 检测路径是否存在
 * @param {*} dirpath 
 * @returns  true 为存在
 */
const checkPath = (dirpath) => {
  try {
    // 判断路径是否已存在
    if (fs.existsSync(dirpath)) {
      return true;
    } else {
      return false;
    }
  } catch (err) {
    return '';
  }
}
/**
 * 判断是文件还是文件夹
 * @param {*} filePath 
 * @returns  file 为文件，folder为目录，''为出错
 */
const isFileOrFolder = (filePath) => {
  try {
    console.log(258, filePath);
    if (!fs.existsSync(filePath)) {
      return {
        code: 300,
        msg: `路径不存在: ${filePath}`,
      };
    } 
    const stats = fs.statSync(filePath);
    if (stats.isFile()) {
      console.log("是文件");
      return "file";
    } 
    if (stats.isDirectory()) {
      console.log("是文件夹");
      return 'folder'
    }
    return ''
  } catch (err) {
    console.log(`${filePath}  文件不存在`);
    return "";
  }
};
/**
 * 创建文件夹
 * @param {*} folderPath 
 * @returns 
 */
const createFolder = (folderPath) => {
  try {
    // 只要路径存在，不管是目录还是文件都无法再创建目录
    if (fs.existsSync(folderPath)) {
      return {
        code: 300,
        msg: `路径已存在: ${folderPath}`,
      };
    } else {
      // 新建文件夹
      fs.mkdirSync(folderPath, { recursive: true });
      res = {
        code: 200,
        msg: `文件夹已成功创建: ${folderPath}`,
      };
      return res;
    }
    
  } catch (err) {
    let res = {
      code: 300,
      msg: "文件夹创建失败：" + err,
    };
    return res;
  }
};
/**
 * 创建空文件
 * @param {*} filePath 
 * @returns 
 */
const createFile = (filePath) => {
  try {
    const stats = fs.statSync(filePath);
    // 判断文件是否已存在
    if (stats.isFile()) {
      return {
        code: 300,
        msg: `文件已存在: ${filePath}`,
      };
    } else {
      // 新建文件
      fs.writeFileSync(filePath, " ", "utf8");
      console.log(`文件已成功创建: ${filePath}`);
      res = {
        code: 200,
        msg: `文件已成功创建: ${filePath}`,
      };
      return res;
    }
  } catch (err) {
    let res = {
      code: 300,
      msg: "文件创建失败：" + err,
    };
    return res;
  }
};
module.exports = {
  readini,
  writeini,
  readDocument,
  asyncReadDocument,
  writeDocument,
  asyncWriteDocument,
  deleteFile,
  asyncDeleteFile,
  createFolder,
  createFile,
  checkPath,
  isFileOrFolder,
};
